package com.freewater.javabase.demo.network.mail;

import jakarta.mail.*;
import jakarta.mail.internet.MimeUtility;
import org.eclipse.angus.mail.pop3.POP3SSLStore;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

public class MainReceive {
    public static void main(String[] args) throws MessagingException, UnsupportedEncodingException {
        final String host = "pop.126.com";
        final String username = "yujishui@126.com";
        final String password = "JMCMTITXUDZZJFUC";
        final int port = 995;

        Properties props = new Properties();
        props.put("mail.store.protocol", "pop3");
        props.put("mail.pop3.host", host);
        props.put("mail.pop3.port", port + "");

        // 启动SSL:
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.port", port + "");
        props.put("mail.pop3.socketFactory.fallback", "true");

        URLName url = new URLName("pop3", host, port, "", username, password);
        Session session = Session.getInstance(props, null);
        //session.setDebug(true);
        POP3SSLStore store = new POP3SSLStore(session, url);
        store.connect();

        final Folder inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_WRITE);

        System.out.println("Total messages: " + inbox.getMessageCount());
        System.out.println("New messages: " + inbox.getNewMessageCount());
        System.out.println("Unread messages: " + inbox.getUnreadMessageCount());
        System.out.println("Deleted messages: " + inbox.getDeletedMessageCount());

        final Message[] messages = inbox.getMessages();
        for (int i = 0; i < messages.length; i++) {
            final Message message = messages[i];
            System.out.println("Mail " + i + ": " + MimeUtility.decodeText(message.getSubject()));
        }
        inbox.close();
        store.close();
    }
}
